//
//  HomeCourseView.m
//  TeacherNet
//
//  Created by slz on 2017/11/7.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "HomeCourseView.h"
#import "CourseTableViewCell.h"
#import "CourseModel.h"



@implementation HomeCourseTableHeaderView
-(instancetype)init
{
    self = [super init];
    if (self){
        UIImageView * bannerImage = [UIImageView new];
        bannerImage.image = [UIImage imageNamed:@"home_test"];
        [self addSubview:bannerImage];
        [bannerImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.top.mas_equalTo(self);
            make.height.mas_equalTo(self.mas_width).multipliedBy(0.36);
        }];
        
        _labelBackView = [UIView new];
        [self addSubview:_labelBackView];
        [_labelBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(bannerImage.mas_bottom).offset(10);
            make.left.and.right.mas_equalTo(self);
            make.bottom.mas_equalTo(self);
        }];
        
        CGFloat labelWidth = (kScreenWidth - 20)/4;
        CGFloat labelHieght = 20;
        
        UIButton * moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setTitle:@"更多" forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
        [moreButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
        moreButton.titleLabel.fontSize = 15;
        moreButton.size = CGSizeMake(labelWidth, labelHieght);
        moreButton.left = 3*labelWidth + 10;
        moreButton.top = 60;
        [_labelBackView addSubview:moreButton];
        
        UIView * lineView = [UIView new];
        lineView.backgroundColor = kLineColor_Gray_Default;
        [_labelBackView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.and.bottom.mas_equalTo(_labelBackView);
            make.height.mas_equalTo(10);
        }];
        
        _labelArr = @[].mutableCopy;

        for (int i = 0; i < 7; i ++){
            UILabel * label = [UILabel new];
            label.textColor = kDark_TextColor_Default;
            label.fontSize = 15;
            label.textAlignment = NSTextAlignmentCenter;
            label.size = CGSizeMake(labelWidth, labelHieght);
            label.left = (i % 4) * labelWidth + 10;
            label.top = i > 3 ? 60 : 15;
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTap:)];
            label.userInteractionEnabled = YES;
            label.tag = i + 1;
            [label addGestureRecognizer:tap];
            [_labelBackView addSubview:label];
            [_labelArr addObject:label];
        }
    }
    return self;
}

- (void)labelTap:(UITapGestureRecognizer *)tap
{
    NSInteger tapIndex = tap.view.tag -1;
    if (tapIndex >  _titleArr.count) return;
    CourseTypeModel * course = [CourseTypeModel yy_modelWithDictionary:_titleArr[tapIndex]];
    if (_delegate && [_delegate respondsToSelector:@selector(headerViewDidClickCourseWithCourseId:andCuorseName:)]){
        [_delegate headerViewDidClickCourseWithCourseId:course.courseTypeId andCuorseName:course.courseTypeTitle];
    }
}

- (void)moreAction{
    if ([self.delegate respondsToSelector:@selector(headerViewDidClickMoreCourse)]) {
        [self.delegate headerViewDidClickMoreCourse];
    }
}

-(void)updateWithTitleArr:(NSArray *)titleArr
{
    _titleArr = titleArr;
    if (!titleArr || titleArr.count == 0) return;
    for (int i = 0; i < titleArr.count; i++) {
        if (i >= _labelArr.count){
            break;
        }
        NSDictionary * course = titleArr[i];
        UILabel * label = _labelArr[i];
        label.text = [course stringValueForKey:@"classify_name" default:@""];
    }
}

@end


@implementation HomeCourseView

- (instancetype)init{
    self = [super init];
    if (self){
        _bestArr = @[];
        _hotArr = @[];
        _recommendArr = @[];
        @weakify(self);
        
        _headerView = [HomeCourseTableHeaderView new];
        _headerView.size = CGSizeMake(kScreenWidth, 120 + kScreenWidth * .36);
        _tableView = [[YWTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self);
            [self requestDate];
        }];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = _headerView;
        [self addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];

        [self requestDate];
    }
    return self;
}

-(void)beginRefresh
{
    if (!_recommendArr || _recommendArr.count == 0)
    [_tableView.mj_header beginRefreshing];
}

-(void)endRefresh
{
    [_tableView.mj_header endRefreshing];
}

- (void)setDelegate:(id<HomeCourseViewDelegate>)delegate{
    _headerView.delegate = delegate;
    _delegate = delegate;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * reuserIndentifier = @"CourseTableViewCell";
    CourseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserIndentifier];
    if (!cell){
        cell = [[CourseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSArray * sourceData = nil;
    if (indexPath.section == 0){
        sourceData = _recommendArr;
    }else if (indexPath.section == 1){
        sourceData = _hotArr;
    }else{
        sourceData = _bestArr;
    }
    NSDictionary * course = sourceData[indexPath.row];
    CourseModel * model = [CourseModel yy_modelWithDictionary:course];
    [cell layoutWithModel:model];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return _recommendArr.count;
    }else if (section == 1){
        return _hotArr.count;
    }else{
        return _bestArr.count;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 37)];
    CALayer * lineLayer = [CALayer new];
    lineLayer.frame = CGRectMake(0, 36, kScreenWidth, 1);
    lineLayer.backgroundColor = kLineColor_Gray_Default.CGColor;
    [backView.layer addSublayer:lineLayer];
    
    UIButton * moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    moreButton.tag = section;
    [moreButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    [moreButton setImage:[UIImage imageNamed:@"home_arrow_right_circle"] forState:UIControlStateNormal];
    moreButton.size = CGSizeMake(25, 25);
    moreButton.centerY = backView.centerY;
    moreButton.right = backView.width - 16;
    [backView addSubview:moreButton];
    
    UILabel * titleLabel = [UILabel new];
    titleLabel.size = CGSizeMake(150, 37);
    titleLabel.left = 15;
    titleLabel.top = 0;
    titleLabel.textColor = kDark_TextColor_Default;
    titleLabel.fontSize = 15;
    [backView addSubview:titleLabel];
    switch (section) {
        case 0:
            titleLabel.text = @"推荐课程";
            break;
            case 1:
            titleLabel.text = @"最热课程";
            break;
            case 2:
            titleLabel.text = @"最新课程";
            break;
        default:
            break;
    }
    
    return backView;
}

- (void)moreAction:(UIButton *)button
{
    if ([_delegate respondsToSelector:@selector(tableSectionHeaderViewClickWithTag:)]){
        [_delegate tableSectionHeaderViewClickWithTag:button.tag];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_delegate respondsToSelector:@selector(tableViewDidClickCourseId:)]){
        NSArray * sourceData = nil;
        if (indexPath.section == 0){
            sourceData = _recommendArr;
        }else if (indexPath.section == 1){
            sourceData = _hotArr;
        }else{
            sourceData = _bestArr;
        }
        NSDictionary * course = sourceData[indexPath.row];
        CourseModel * model = [CourseModel yy_modelWithDictionary:course];

        [_delegate tableViewDidClickCourseId:model.courseId];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 37;
}

- (void)requestDate{
    [ZYNetWorking getWithUrl:kAPI_HOME_COURSE params:nil Cache:YES refreshCache:YES success:^(id response) {
        [self endRefresh];
        [self updateDataWithJson:[MFWJson jsonWithObject:response]];
    } fail:^(NSError *error) {
        [self endRefresh];
        [self showTip:error.localizedDescription];
    }];
//    [BaseHttpTool get:kAPI_HOME_COURSE params:nil success:^(id responseObj) {
//
//    } failure:^(NSError *error) {
//
//    }];
}

- (void)updateDataWithJson:(MFWJson *)json{
    MFWJson * classifyListJson = [json jsonForKey:@"classifyList"];
    NSArray * arr = [classifyListJson toArray];
    [_headerView updateWithTitleArr:arr];
    
    MFWJson * recommend = [json jsonForKey:@"recommendList"];
    _recommendArr = [recommend toArray];
    
    MFWJson * hotJson = [json jsonForKey:@"hotList"];
    _hotArr = [hotJson toArray];
    
    MFWJson * newJson = [json jsonForKey:@"newList"];
    _bestArr = [newJson toArray];
    [_tableView reloadData];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
